package com.bluemsun.naturallanguageprocessing.service.impl;

import com.bluemsun.naturallanguageprocessing.Aspect.annotation.IsUserOfFavorite;
import com.bluemsun.naturallanguageprocessing.common.ServerResponse;
import com.bluemsun.naturallanguageprocessing.dao.CollectionMapper;
import com.bluemsun.naturallanguageprocessing.entity.Favorites;
import com.bluemsun.naturallanguageprocessing.service.ICollectService;
import com.bluemsun.naturallanguageprocessing.vo.QuestionVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service("iCollectService")
public class CollectServiceImpl implements ICollectService {

    @Resource
    private CollectionMapper collectionMapper;

    private static final Logger logger = LoggerFactory.getLogger(CollectServiceImpl.class);

    @Override
    public ServerResponse<List<Favorites>> queryUserCollection(Integer userId) {
        List<Favorites> favorites = collectionMapper.queryCollections(userId);
        if (favorites.isEmpty()){
            return ServerResponse.createByErrorMessage("空空如也");
        }
        return ServerResponse.createBySuccess("返回用户收藏",favorites);
    }

    @Override
    @Transactional
    @IsUserOfFavorite
    public ServerResponse userDoCollect(Integer userId, Set<Integer> newIds, Integer questionId) {
        Set<Integer> result = new HashSet<>();
        // 先从数据库拿出来这个问题原来的存储的文件夹ID
        Set<Integer> originIds = collectionMapper.queryUserFavoritesOfQuestion(questionId, userId);
        // 如果要收藏到的文件夹ID和数据库里面的一致，表示前后没变，直接返回
        String newString = newIds.toString();
        String originString = originIds.toString();
        if (newString.equals(originString)){
            return ServerResponse.createBySuccessMessage("收藏成功");
        }
        // 分别做差集
        // 对原始的数据做差集
        result.addAll(originIds);
        result.removeAll(newIds);
        // 得到原始数据差集，根据差集对数据库进行删除操作，即，删除问题所在的文件夹
        Integer delete = null;
        try{
            delete = collectionMapper.deleteQuestionOfFavorite(result, questionId);
        }catch (RuntimeException e){
            logger.error(e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
        // 对新的数据做差集
        result.clear();
        result.addAll(newIds);
        result.removeAll(originIds);
        // 得到新的数据的差集，根据差集对数据库做插入操作，即，增加问题所在文件夹
        Integer integer = null;
        try{
            // 用户有这个文件夹,接下来进行收藏
            if (result.size()!=0){
                integer = collectionMapper.addCollection(result, questionId);
            }
        }catch (RuntimeException e){
            logger.error(e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
        return ServerResponse.createBySuccessMessage("收藏成功");
    }

    @Override
    public ServerResponse<Object> queryUserFavorites(Integer userId,Integer questionId) {
        List<Favorites> favorites = collectionMapper.queryUserFavorites(userId,questionId);
        if (favorites.isEmpty()) {
            logger.error("数据库中不存在该用户的收藏夹，用户Id为{}",userId);
            return ServerResponse.createByErrorMessage("您没有收藏夹,请您创建收藏夹");
        }
        List<QuestionVO> questionVOList = null;
        for (Favorites favorite : favorites) {
            questionVOList = favorite.getQuestionVOList();
            if (questionVOList.isEmpty()) {
                favorite.setIsCollected(0);
                favorite.setQuestionVOList(null);
            } else if (questionVOList.get(0).getId().equals(questionId)) {
                favorite.setIsCollected(1);
                favorite.setQuestionVOList(null);
            }
        }
        return ServerResponse.createBySuccess("返回收藏夹信息",favorites);
    }

    @Override
    @IsUserOfFavorite
    @Transactional
    public ServerResponse<Object> modifyName(Integer userId, Integer favoriteId,String newName) {
        Integer integer = collectionMapper.modifyName(newName, favoriteId);
        return ServerResponse.createBySuccess("收藏夹名称修改成功");
    }

    @Override
    @Transactional
    @IsUserOfFavorite
    public ServerResponse<Object> deleteFavorite(Integer userId, Integer favoriteId) {
        //先删除收藏夹下面的所有问题
        Integer integer = collectionMapper.deleteQuestionsOfFavorite(favoriteId);
        //再删除收藏夹
        Integer deleteFavorite = collectionMapper.deleteFavorite(favoriteId);
        return ServerResponse.createBySuccess("删除收藏夹成功");
    }

    @Override
    @Transactional
    public ServerResponse<Object> createFavorite(Integer userId, String favoriteName) {
        Integer integer = null;
        Favorites favorites = new Favorites();
        try{
            favorites.setName(favoriteName);
            integer = collectionMapper.addFavorite(userId, favorites);
        }catch (RuntimeException e){
            logger.error("用户创建文件夹出错,用户ID为{},收藏夹名称为{}",userId,favoriteName);
            logger.error(e.toString());
            e.printStackTrace();
            throw new RuntimeException("对不起,收藏夹创建失败");
        }
        if (integer == null){
            logger.error("用户创建文件夹失败,sql返回值为空,用户ID为{},收藏夹名称为{}",userId,favoriteName);
            return ServerResponse.createByErrorMessage("对不起,收藏夹创建失败");
        }else {
            return ServerResponse.createBySuccess("收藏夹创建成功",favorites);
        }
    }

    @Override
    @Transactional
    @IsUserOfFavorite
    public ServerResponse<Object> cancelCollected(Integer userId, Integer favoriteId, Set<Integer> questionIds) {
        Integer integer = collectionMapper.deleteSomeQuestionsOfFavorite(favoriteId, questionIds);
        if (integer == null) {
            return ServerResponse.createByErrorMessage("删除收藏失败");
        }
        return ServerResponse.createBySuccessMessage("删除收藏成功");
    }


}
